"""
    Author:
    Date: 2019-12-15

    用户银行卡管理类
"""

from entities import user_mgr
from entities.consts import *
from utils import db


def get_user_bank_info(mobile):
    """ 用户用户的银行信息 """
    sql = f'''
        SELECT      *
        FROM        cmf_users_bank
        WHERE       mobile=%(mobile)s
        LIMIT       1;
    '''
    params = {
        'mobile': mobile,
    }
    data = db.query_data_from_db(sql, params)
    return data[0] if data else None


def save_user_bank_info(uid, mobile, real_name, cert_no, bank_name, bank_address, bank_branch, bank_card_number):
    """ 创建或更新用户的银行信息 """
    bank_info = get_user_bank_info(mobile)
    if bank_info is None:
        sql = '''
            INSERT INTO cmf_users_bank
            SET         mobile=%(mobile)s,
                        uid=%(uid)s,
                        real_name=%(real_name)s,
                        cert_no=%(cert_no)s,
                        bank_name=%(bank_name)s,
                        bank_address=%(bank_address)s,
                        bank_branch=%(bank_branch)s,
                        bank_card_number=%(bank_card_number)s;
        '''
    else:
        sql = '''
            UPDATE      cmf_users_bank
            SET         real_name=%(real_name)s,
                        cert_no=%(cert_no)s,
                        bank_name=%(bank_name)s,
                        bank_address=%(bank_address)s,
                        bank_branch=%(bank_branch)s,
                        bank_card_number=%(bank_card_number)s
            WHERE       mobile=%(mobile)s AND
                        uid=%(uid)s
            LIMIT       1;
        '''
    params = {
        'uid': uid,
        'mobile': mobile,
        'real_name': real_name,
        'cert_no': cert_no,
        'bank_name': bank_name,
        'bank_address': bank_address,
        'bank_branch': bank_branch,
        'bank_card_number': bank_card_number,
    }
    affected = db.execute_sql(sql, params)
    return affected == 1


if __name__ == '__main__':
    print('ok')
